<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>地区数据调试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .debug-info { background: #f8f9fa; padding: 15px; margin: 10px 0; border-radius: 5px; }
        .error { background: #f8d7da; color: #721c24; }
        .success { background: #d4edda; color: #155724; }
        select { padding: 8px; margin: 10px 0; min-width: 300px; }
        button { padding: 8px 16px; margin: 5px; }
        pre { background: #f1f1f1; padding: 10px; overflow-x: auto; }
    </style>
</head>
<body>
    <h1>🔍 地区数据调试页面</h1>
    
    <div class="debug-info">
        <h3>当前页面信息</h3>
        <p><strong>页面URL:</strong> <span id="pageUrl"></span></p>
        <p><strong>API地址:</strong> <span id="apiUrl"></span></p>
        <p><strong>时间:</strong> <span id="currentTime"></span></p>
    </div>
    
    <div>
        <button onclick="testDirectAPI()">直接测试API</button>
        <button onclick="testWithFetch()">使用Fetch测试</button>
        <button onclick="clearLog()">清除日志</button>
    </div>
    
    <div>
        <label>乡镇街道选择：</label>
        <select id="regionSelect">
            <option value="">加载中...</option>
        </select>
    </div>
    
    <div id="debugLog"></div>

    <script>
        const API_BASE_URL = 'http://localhost:3001/api';
        
        // 更新页面信息
        document.getElementById('pageUrl').textContent = window.location.href;
        document.getElementById('apiUrl').textContent = API_BASE_URL;
        document.getElementById('currentTime').textContent = new Date().toLocaleString();
        
        function log(message, type = 'info') {
            const logDiv = document.getElementById('debugLog');
            const timestamp = new Date().toLocaleTimeString();
            const className = type === 'error' ? 'debug-info error' : 
                             type === 'success' ? 'debug-info success' : 'debug-info';
            
            logDiv.innerHTML += `
                <div class="${className}">
                    <strong>[${timestamp}]</strong> ${message}
                </div>
            `;
            logDiv.scrollTop = logDiv.scrollHeight;
        }
        
        function clearLog() {
            document.getElementById('debugLog').innerHTML = '';
        }
        
        async function testDirectAPI() {
            log('🔗 开始直接API测试...');
            
            try {
                log('📡 发送请求到: ' + API_BASE_URL + '/regions?parent_id=0');
                
                const response = await fetch(API_BASE_URL + '/regions?parent_id=0', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                log(`📊 响应状态: ${response.status} ${response.statusText}`);
                log(`📋 响应头: ${JSON.stringify(Object.fromEntries(response.headers.entries()))}`);
                
                if (response.ok) {
                    const data = await response.json();
                    log(`✅ 请求成功！数据类型: ${typeof data}`, 'success');
                    log(`📦 数据结构: code=${data.code}, message="${data.message}", data.length=${data.data ? data.data.length : 'undefined'}`, 'success');
                    
                    if (data.data && Array.isArray(data.data)) {
                        log(`🎯 成功获取 ${data.data.length} 个地区`, 'success');
                        
                        // 填充下拉菜单
                        const select = document.getElementById('regionSelect');
                        select.innerHTML = '<option value="">请选择乡镇街道</option>';
                        
                        data.data.forEach((region, index) => {
                            const option = document.createElement('option');
                            option.value = region.id;
                            option.textContent = region.name;
                            select.appendChild(option);
                            
                            if (index < 5) { // 只显示前5个
                                log(`📍 地区 ${index + 1}: ${region.name} (ID: ${region.id})`);
                            }
                        });
                        
                        if (data.data.length > 5) {
                            log(`📍 ... 还有 ${data.data.length - 5} 个地区`);
                        }
                        
                        log(`✅ 下拉菜单已更新`, 'success');
                    } else {
                        log(`❌ 数据格式错误: data字段不是数组`, 'error');
                        log(`🔍 实际数据: <pre>${JSON.stringify(data, null, 2)}</pre>`);
                    }
                } else {
                    log(`❌ 请求失败: ${response.status}`, 'error');
                    const errorText = await response.text();
                    log(`🔍 错误内容: ${errorText}`, 'error');
                }
            } catch (error) {
                log(`❌ 网络错误: ${error.message}`, 'error');
                log(`🔍 错误详情: ${error.stack}`, 'error');
            }
        }
        
        async function testWithFetch() {
            log('🔄 使用标准Fetch测试...');
            
            try {
                const url = `${API_BASE_URL}/regions?parent_id=0`;
                log(`📡 请求URL: ${url}`);
                
                const response = await fetch(url);
                log(`📊 Fetch响应: status=${response.status}, ok=${response.ok}`);
                
                const text = await response.text();
                log(`📝 原始响应文本长度: ${text.length}`);
                log(`📝 原始响应内容: ${text.substring(0, 200)}...`);
                
                try {
                    const data = JSON.parse(text);
                    log(`✅ JSON解析成功`, 'success');
                    log(`📦 解析后数据: ${JSON.stringify(data, null, 2).substring(0, 500)}...`);
                } catch (parseError) {
                    log(`❌ JSON解析失败: ${parseError.message}`, 'error');
                }
                
            } catch (error) {
                log(`❌ Fetch错误: ${error.message}`, 'error');
            }
        }
        
        // 页面加载完成后自动测试
        document.addEventListener('DOMContentLoaded', function() {
            log('📄 页面加载完成');
            log('🌐 User Agent: ' + navigator.userAgent);
            log('🔧 开始自动测试...');
            
            setTimeout(() => {
                testDirectAPI();
            }, 1000);
        });
        
        // 监听下拉菜单变化
        document.getElementById('regionSelect').addEventListener('change', function() {
            const selectedValue = this.value;
            const selectedText = this.options[this.selectedIndex].text;
            if (selectedValue) {
                log(`🎯 用户选择: ${selectedText} (值: ${selectedValue})`, 'success');
            }
        });
    </script>
</body>
</html> 